var util = require('../../libs/util.js');
//获取应用实例
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    unitArray: util.goodsUnit,
    unitIndex: 0,
    keyboardHeight: 0,
    isIOS: false,
    is_custom_distance:false,
    price_driver_show:true,
    shop_time_fromwh:false,
    driver_operation_exception_warn:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;
    // const platform = wx.getSystemInfoSync().platform
    // const isIOS = platform === 'ios'
    // this.setData({ isIOS})
    // this.updatePosition(0)
    // let keyboardHeight = 0
    // wx.onKeyboardHeightChange(res => {
    //   if (res.height === keyboardHeight) return
    //   const duration = res.height > 0 ? res.duration * 1000 : 0
    //   keyboardHeight = res.height
    //   setTimeout(() => {
    //     wx.pageScrollTo({
    //       scrollTop: 0,
    //       success() {
    //         that.updatePosition(keyboardHeight)
    //         that.editorCtx.scrollIntoView()
    //       }
    //     })
    //   }, duration)

    // })

    if (e.id) {
      this.setData({
        id: e.id
      })
    }
    this.loadData();
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const { windowHeight, platform } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({ editorHeight, keyboardHeight })
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context;
      if(that.data.delivery_requirement){
        that.editorCtx.setContents({
          html: util.html_decode(that.data.delivery_requirement)
        })
      }
    }).exec()
    
  },
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)
  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({ formats })
  },
  saveRequirement:function(){
    var that = this; 
    that.editorCtx.getContents({
      success:function(res){
         console.log(res)
         var html = util.html_encode(res.html);
         that.setData({
          delivery_requirement:html
         })
         wx.showLoading({
          title: '提交中...',
        })
         util.putData("/atapi/warehouse/warehouse/editRequirement", {
          'ID': that.data.ID,
          'delivery_requirement': that.data.delivery_requirement
        }, function (res, error) {
          console.log(res); console.log(error)
          if (res.data.success) {
            wx.showToast({
              title: "保存成功",
              icon: "success",
              duration: 3000
            });
            that.hideModal();
          }else{
            wx.showToast({
              title: "保存失败",
              image: '/images/wrong.png',
              duration: 3000
            });
          }
        });
      },
      fail:function(err){
        console.log(err)
        wx.showToast({
          title: "保存失败",
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    })
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    var value = e.detail.value;
    item_value[item] = value;
    console.log(value)
    console.log(value.length)
    console.log(isNaN(value))
    if(item == 'tp_threshold_min' || item == 'tp_threshold_max'){
      if(value.length == 1 && value == '-'){

      }else if(value.length == 1 && value != '-'){
          if(isNaN(value) == true){
            item_value[item] = '';
          }
      }else if(value.length > 1){
        if(isNaN(value) == true){
          item_value[item] = '';
        }
      }
    }
    this.setData(item_value);
  },
  bindPickerChange: function (e) {
    this.setData({
      unitIndex: e.detail.value
    })
  },
  switchChange(e) {
    console.log(e)
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  loadData: function () {
    var that = this; 
    wx.showLoading({
      title: '加载中',
    })
    util.postData("/zhc/datalist/getDataByListId", {
      "list_id": "C1FFD7BD-140A-4842-A62C-86A330B9DDCF",
      "page": {
        "size": 1,
        "current": 1,
        "orders": [
          {
            "column": "a.ADD_TIME",
            "asc": "false"
          }
        ]
      },
      "data": {
        "field": ""
      },
      "repeat_field": [],
      "condition": " ID='"+that.data.id+"' ",
      "virtual_field": []
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success && res.data?.result?.records.length > 0) {
        var dataList = res.data.result.records[0];
        that.setData(dataList);
        that.setData({
          unitIndex: that.data.unitArray.indexOf(dataList.unit),
          "addressComponent.province": dataList.province,
          "addressComponent.city": dataList.city,
          "addressComponent.area": dataList.area,
          tags: dataList.tags ? String(dataList.tags).split(",") : [],
          delivery_requirement: util.html_decode(dataList.delivery_requirement),
          is_custom_distance:dataList.is_custom_distance == 1?true:false,
          price_driver_show:dataList.price_driver_show == 1?true:false,
          shop_time_fromwh:that.data.shop_time_fromwh== 1?true:false,
          driver_operation_exception_warn:that.data.driver_operation_exception_warn== 1?true:false
        });
        
        
      }
      that.setData({
        vehicleTag: util.vehicleTag
      })
      wx.hideLoading();
    });
  },
  backToList:function(){
    wx.redirectTo({
      url: '/pages/enterprise/warehouse'
    })
  },
  setRouterConfig: function () {
    var data = this.data;
    wx.navigateTo({
      url: '/pages/schedule/apps/router_config?id=' + data.ID + '&name=' + data.name + '&coord=' + data.coord + '&strategy=' + data.strategy + '&routing_type=' + data.routing_type
    })
  },
  formSubmit:function(){
    var that = this;
    var dataList = that.data;
    var tp_threshold_max = that.data.tp_threshold_max;
    var tp_threshold_min = that.data.tp_threshold_min;
    if (isNaN(tp_threshold_max) == true) {
      tp_threshold_max = '';
    }
    if (isNaN(tp_threshold_min) == true) {
      tp_threshold_min = '';
    }
    if ((tp_threshold_max == '' && tp_threshold_min != '') || (tp_threshold_max != '' && tp_threshold_min == '')) {
      wx.showToast({
        title: "温度阈值缺少",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (tp_threshold_max != '' && tp_threshold_min != '' && Number(tp_threshold_max) != 0 && Number(tp_threshold_max||0) <= Number(tp_threshold_min||0)) {
      wx.showToast({
        title: "温度阈值不合法",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    var hr_threshold_max = that.data.hr_threshold_max;
    var hr_threshold_min = that.data.hr_threshold_min;
    if (isNaN(hr_threshold_max) == true) {
      hr_threshold_max = '';
    }
    if (isNaN(hr_threshold_min) == true) {
      hr_threshold_min = '';
    }
    if ((hr_threshold_max == '' && hr_threshold_min != '') || (hr_threshold_max != '' && hr_threshold_min == '')) {
      wx.showToast({
        title: "湿度阈值缺少",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    console.log(hr_threshold_max)
    console.log(hr_threshold_min)
    console.log(Number(hr_threshold_max||0) <= Number(hr_threshold_min||0))
    if (hr_threshold_max != '' && hr_threshold_min != '' && Number(hr_threshold_max) != 0 && Number(hr_threshold_max||0) <= Number(hr_threshold_min||0)) {
      wx.showToast({
        title: "湿度阈值不合法",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    var taxrate = that.data.taxrate;
    if (isNaN(taxrate) == true || Number(taxrate) < 0 || Number(taxrate) > 100){
      wx.showToast({
        title: "税率不合法",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    wx.showLoading({
      title: '提交中...',
    })
    let data = {
      "formId":"7E0C0F3D-5B14-4EB3-AFFB-592B78EF020A",
      "list_id":"",
      "data":[
          {
              "dataId":dataList.ID,
              "target":{
                'name': that.data.name || dataList.name,
                'mark': that.data.mark || dataList.mark,
                'sub_mark': that.data.sub_mark || dataList.sub_mark,
                'abbreviation': that.data.mark || dataList.abbreviation,
                'address': that.data.address || dataList.address,
                'unit': that.data.unitArray[that.data.unitIndex] || dataList.unit,
                'coord': that.data.coord || dataList.coord,
                'loading_time': that.data.loading_time || dataList.loading_time,
                'loading_rule': that.data.loading_rule || dataList.loading_rule,
                'routing_type': that.data.routing_type || dataList.routing_type,
                'strategy': that.data.strategy || dataList.strategy,
                'reach_distance_limit': that.data.reach_distance_limit || dataList.reach_distance_limit,
                'tp_threshold_max': tp_threshold_max,
                'tp_threshold_min': tp_threshold_min,
                'hr_threshold_max':hr_threshold_max,
                'hr_threshold_min':hr_threshold_min,
                'monthly_income':that.data.monthly_income,
                'province': that.data.addressComponent.province,
                'city': that.data.addressComponent.city,
                'area': that.data.addressComponent.area,
                'payment_mode': that.data.payment_mode,
                'taxrate':that.data.taxrate,
                'customer':that.data.customer||'',
                'project':that.data.project||'',
                'monthly_contract_company':that.data.monthly_contract_company||0,
                'monthly_contract_outer':that.data.monthly_contract_outer||0,
                'is_custom_distance':that.data.is_custom_distance?1:0,
                'price_driver_show':that.data.price_driver_show?1:0,
                'shop_time_fromwh':that.data.shop_time_fromwh?1:0,
                'driver_operation_exception_warn':that.data.driver_operation_exception_warn?1:0,
                'no_vehicle_warn_time':that.data.no_vehicle_warn_time
              }
          }],
      "condition":""
      }
    util.postData("/sys/form/commonUpdate", data, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        wx.showToast({
          title: "保存成功",
          icon: "success",
          duration: 3000
        });
      }else{
        wx.showToast({
          title: "保存失败",
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    });
  },
  chooseLocation: function () {
    var that = this;
    wx.chooseLocation({
      success(res) {
        console.log(res)
        var latitude = res.latitude;
        var longitude = res.longitude;
        that.setData({
          coord: latitude + ',' + longitude,
          address: that.data.address ? that.data.address : res.address,
          name: that.data.name ? that.data.name : res.name
        })
        util.getData("/xypapi/map/routerCalculate/geocode", {
          latitude: res.latitude,
          longitude: res.longitude
        }, function (res, error) {
          console.log(res); console.log(error)
          if (res.data.success) {
            that.setData({
              "addressComponent.province": res.data.component.province,
              "addressComponent.city": res.data.component.city,
              "addressComponent.area": res.data.component.district
            });
          }
        });
      }
    })
  },
  showLocation:function(){
    var that = this;
    var coord = that.data.coord
    if (coord) {
      coord = coord.split(',');
      wx.openLocation({
        latitude: Number(coord[0]),
        longitude: Number(coord[1]),
        scale: 18
      })
    } else {
      wx.showToast({
        title: "请先选择位置",
        image: '/images/wrong.png',
        duration: 3000
      });
    }
  },
  addTag: function (e) {
    var that = this;
    var tag = e.currentTarget.dataset.tag;
    var id = that.data.id;
    var tags = that.data.tags;
    var newtag = '';
    var tagArray = tags;
    if (!tagArray) {
      tagArray = [];
      tagArray.push(tag);
      newtag = tagArray.join(",");
    } else {
      if (tagArray.indexOf(tag) > -1) {
        wx.showToast({
          title: '同名分类已存在',
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      } else {
        tagArray.push(tag);
        newtag = tagArray.join(",");
      }
    }
    that.setData({
      tags: tags,
      modalName: null
    });
    if (newtag) {
      that.saveNewTag(id, newtag);
    }
  },
  addNewTag: function (e) {
    var that = this;
    var tag = that.data.newtag;
    if (!tag) {
      wx.showToast({
        title: '请输入标签名称',
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    var id = that.data.id;
    var tags = that.data.tags;
    var newtag = '';
    var tagArray = tags;
    if (!tagArray) {
      tagArray = [];
      tagArray.push(tag);
      newtag = tagArray.join(",");
    } else {
      if (tagArray.indexOf(tag) > -1) {
        wx.showToast({
          title: '同名分类已存在',
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      } else {
        tagArray.push(tag);
        newtag = tagArray.join(",");
      }
    }
    that.setData({
      tags: tags,
      modalName: null
    })
    if (newtag) {
      that.saveNewTag(id, newtag);
    }
  },
  saveNewTag: function (id, tags) {
    util.postData("/atapi/warehouse/warehouse/saveVehicleTag", {
      id: id,
      tags: tags
    }, function (res, error) {
      if (res.data.success) {
        wx.showToast({
          title: '设置成功',
          icon: 'success',
          duration: 2000,
          success: function () {

          }
        })

      } else {
        wx.showToast({
          title: '设置失败',
          icon: 'success',
          duration: 2000
        })
      }
    });
  },
  deleteTag: function (e) {
    var that = this;
    var tag = e.currentTarget.dataset.tag;
    var id = that.data.id;
    var tags = that.data.tags;
    var newtag = '';
    newtag = tags = util.arrayDeleteItem(tags, tag);
    if (newtag) {
      wx.showModal({
        title: '温馨提示',
        content: '确认要删除分类【' + tag + '】吗？',
        success(res) {
          if (res.confirm) {
            that.setData({
              tags: tags
            });
            that.saveNewTag(id, newtag);
          }
        }
      })
    }
  },
  showModal(e) {
    var that = this;
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
    if(e.currentTarget.dataset.target == 'paymentModeModal'){
      var payment_mode = that.data.payment_mode||app.globalData.payment_mode;
      var _payment_mode = payment_mode.split(",");
      var payment_mode_list = [];
      if(_payment_mode.length > 0){
          for(var i=0;i<_payment_mode.length;i++){
            var _pm = String(_payment_mode[i]).split(":")
            payment_mode_list.push({
               name:_pm[0],
               value:String(_pm[1]).replace('%','')
            })
          }
      }
      that.setData({
         payment_mode_list:payment_mode_list
      })
   }
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  addPmItem:function(){
    var that = this;
    var payment_mode_list = that.data.payment_mode_list;
    payment_mode_list.push({name:'',value:''});
    that.setData({
      payment_mode_list:payment_mode_list
    })
  },
  deletePmItem:function(e){
    var that = this;
    var payment_mode_list = that.data.payment_mode_list;
    var index = e.currentTarget.dataset.index;
    var _payment_mode_list = [];
    for(var i=0;i<payment_mode_list.length;i++){
      if(i != index){
        _payment_mode_list.push(payment_mode_list[i])
      }
   }
    that.setData({
      payment_mode_list:_payment_mode_list
    })
  },
  pminput:function(e){
    var that = this;
    var type = e.currentTarget.dataset.type;
    var index = e.currentTarget.dataset.index;
    var value = e.detail.value;
    var payment_mode_list = that.data.payment_mode_list;
    for(var i=0;i<payment_mode_list.length;i++){
       if(i == index){
          if(type == 'name'){
            payment_mode_list[i].name = value;
          }
          if(type == 'value'){
            if(isNaN(value) == false){
              payment_mode_list[i].value = value;
            }else{
              wx.showToast({
                title: "请输入数字",
                image: '/images/wrong.png',
                duration: 3000
              });
            }
          }
       }
    }
    that.setData({
      payment_mode_list:payment_mode_list
    })
  },
  //保存付款方式
  savePaymentMode: function (e) {
    var that = this;
    var payment_mode_list = that.data.payment_mode_list;
    var _payment_mode = new Array();
    var isPass = true;
    var percentage = 0;
    if(payment_mode_list.length > 0){
      for(var i=0;i<payment_mode_list.length;i++){
        percentage += Number(payment_mode_list[i].value);
        if(payment_mode_list[i].name == '' || payment_mode_list[i].value == ''){
          wx.showToast({
            title: "有空的条目",
            image: '/images/wrong.png',
            duration: 3000
          });
          isPass = false;
          return false;
        }
        _payment_mode[i] = payment_mode_list[i].name+':'+payment_mode_list[i].value+'%'
     }
     if(percentage != 100){
        wx.showToast({
          title: "总比率不等100",
          image: '/images/wrong.png',
          duration: 3000
        });
        isPass = false;
        return false;
     }
      that.setData({
        payment_mode:_payment_mode.join(',')
      })
    }else{
      that.setData({
        payment_mode:''
      })
    }
    
    if(isPass){
      that.setData({
        modalName: null
      })
    }
  },
  selectCustomer: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/index/customerList'
    })
  },
  selectProject: function (e) {
    var that = this;
    if(!that.data.customer){
      wx.showToast({
        title: "请先选择客户",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    wx.navigateTo({
      url: '/pages/index/projectList?customer='+that.data.customer
    })
  },
  configGuide:function(){

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
     var that = this;
     wx.getStorage({
       key: 'path_customer',
       success: function (res) {
         console.log(res)
         if (res.data) {
           that.setData({
             customerName: res.data.name,
             customer:res.data.value
           });
           wx.removeStorage({
             key: 'path_customer',
             success: function (res) {
             }
           });
         }
       }
     });
     wx.getStorage({
      key: 'path_project',
      success: function (res) {
        console.log(res)
        if (res.data) {
          that.setData({
            projectName: res.data.name,
            project:res.data.value
          });
          wx.removeStorage({
            key: 'path_customer',
            success: function (res) {
            }
          });
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})